package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.constans.wemedia.WemediaContans;
import com.usian.common.kafka.NewsAutoScanConstant;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.*;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper nmMapper;

    @Autowired
    private WmMaterialMapper mMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) return paramError;
        //2.分页参数校验   已经设置默认分页参数
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) wrapper.eq(WmNews::getStatus, dto.getStatus());
        if (StringUtils.isNotBlank(dto.getKeyword())) wrapper.like(WmNews::getTitle, dto.getKeyword());
        if (dto.getChannelId() != null) wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        wrapper.eq(WmNews::getUserId, wmUser.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> newsPage = new Page<>(dto.page, dto.size);
        IPage<WmNews> page = page(newsPage, wrapper);
        PageResponseResult result = new PageResponseResult(dto.page, dto.size, (int) page.getTotal());
        result.setData(page.getRecords());
        result.setHost(fileServerUrl);

        return result;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        //1.检查参数
        if (wmNews == null || StringUtils.isBlank(wmNews.getContent())) return paramError;

        /*//2.保存或修改文章
        创建新闻对象  将前端传过来的新闻对象赋值给新对象
        */
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNews, news);//把dto的字段内容copy给wmNews   dto(前端参数对象) = wmNews(目标数据)  BeanUtils.copyProperties可以自动识别类型
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())) news.setType(null);//类型为-1为自动，此处先给null 随后在做处理
        if (wmNews.getImages() != null && wmNews.getImages().size() > 0) {
            StringBuffer buffer = new StringBuffer();
            for (String image : wmNews.getImages()) {//将封面图以逗号连接的方式拼成一个字符串，将其赋值为字段images(新闻引用的图片)
                buffer.append(image.replace(fileServerUrl, "")).append(",");
            }
            news.setImages(buffer.substring(0, (buffer.length() - 1)));
        }
        saveWmNews(news, isSubmit);//保存或修改文章

        //3.关联文章和素材关系
        String content = wmNews.getContent();//获取内容拿到图片
        JSONArray array = JSON.parseArray(content);
        List<String> materials = new ArrayList<>();
        for (Object o : array) {
            JSONObject object = JSON.parseObject(o.toString());
            if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String url = object.getString("value");
                materials.add(url.replace(fileServerUrl, ""));
            }
        }

        //3.1关联内容这种的图片和素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            if (materials.size() != 0) saveRelativeInfoForContent(materials, news.getId());
            saveRelativeInfoForCover(wmNews, materials, news);
        }
        return null;
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.检查参数
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不能缺少");
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(fileServerUrl);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不能缺少");
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_SINGLE_IMAGE))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        //4.去除素材和文章得关系
        nmMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return paramSuccess;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        //4.修改文章状态，同步到app端（后期做）   TODO--上下架状态
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            HashMap<String, Object> mesMap = new HashMap<>();
            mesMap.put("enable",dto.getEnable());
            mesMap.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send("wediaNews",JSON.toJSONString(mesMap));
        }
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //检查分页参数   此处已经给定默认参数

        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle()))dto.setTitle("%"+dto.getTitle()+"%");
        //分页查询
        List<WmNewsVo> voList = baseMapper.findListAndPage(dto);
        //查询数量
        int count = baseMapper.findListCount(dto);

        //结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(voList);
        return responseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章（新闻对象）信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        //3.封装WmNewsVo信息
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        return wmNewsVo;
    }

    /**
     * 设置封面图片和素材的关系
     *
     * @param materials 内容中图片的集合
     * @param wmNews    前端传过来的新闻对象
     * @param news      刚刚保存的文章对象
     * @return
     */
    private void saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materials, WmNews news) {
        List<String> images = wmNews.getImages();//前端传过来的封面图集合
        if (wmNews.getType().equals(WemediaContans.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() == 1 || materials.size() == 2) {
                images = Arrays.asList(materials.get(0));
                news.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
            } else if (materials.size() > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                news.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
            } else news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            //修改文章信息
            if (images != null && images.size() != 0) {
                news.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));
            }
            updateById(news);
        }
        //保存封面图片和素材的关系
        if (images != null && images.size() != 0) {
            saveRelativeInfoForImage(images, news.getId());
        }
    }

    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer id) {
        List<String> image = images.stream().map(s -> s.replace(fileServerUrl, "")).collect(Collectors.toList());
        return saveRelativeInfo(image, id, WemediaContans.WM_COVER_REFERENCE);
    }

    /**
     * @param materials
     * @param id
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer id) {
        return saveRelativeInfo(materials, id, WemediaContans.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存关系
     *
     * @param materials
     * @param id
     * @param wmContentReference
     */
    private ResponseResult saveRelativeInfo(List<String> materials, Integer id, Short wmContentReference) {
        //1.获取数据库中的素材信息
        List<WmMaterial> list = mMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        List<String> idList = new ArrayList<>();
        list.forEach(m -> idList.add(m.getId() + ""));
        nmMapper.saveRelationsByContent(idList, id, wmContentReference);//wmContentReference内容引用
        return null;
    }

    /**
     * 保存或修改文章
     *
     * @param news
     * @param isSubmit
     */
    private void saveWmNews(WmNews news, Short isSubmit) {
        news.setStatus(isSubmit);
        news.setUserId(WmThreadLocalUtils.getUser().getId());
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setStatus((short) 1);
        //有ID更新：更新删了再存   无ID新增保存
        if (news.getId() == null) {
            save(news);
        } else {
            //如果用户重新编辑后进行保存，对后来来讲其实就是更新新闻数据，因为在后边会同意处理新闻和素材的关系数据，所以在这里对于之前存在的所有关系进行解除
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmNewsMaterial::getNewsId, news.getId());//根据新闻的Id删除  新闻Id和素材Id是一对多的关系  删除所有和这个新闻有关联的素材
            nmMapper.delete(wrapper);
            updateById(news);
        }
        //当文章发布了或者修改了,将文章ID发送到kafka队列
        kafkaTemplate.send(NewsAutoScanConstant.WM_NEWS_AUTO_SCAN_TOPIC, news.getId().toString());
    }
}
